<?php
namespace cms\component\smarty;

use yii;
use yii\smarty\ViewRenderer;
use app\models\BasicConfig;
use app\models\CoreConfig;
use app\models\GlobalVariable;
use app\models\ContentFlag;
use app\models\Content;
use app\models\ContentSearch;
use app\models\ContentCategory;
use app\models\Poster;
use app\models\Nav;
use cms\component\page\Page;
use common\component\tool\Tool;
use yii\db\Expression;
use yii\helpers\Html;

/*继承ViewRenderer 为了拓展smarty插件*/
class MyViewRenderer extends ViewRenderer
{
    protected $lang;
    protected $app_id;

    public function init()
    {
        parent::init();
        $this->lang = Yii::$app->params['lang'];
        $this->app_id = Yii::$app->params['app_id'];
        $this->addPlugin();
    }

    /*增加标签插件*/
    public function addPlugin()
    {
        // var_dump($this->smarty);
        $this->smarty->registerPlugin('function', 'webinfo', [$this, 'getCoreConfig']);//核心标签
        $this->smarty->registerPlugin('function', 'global', [$this, 'getGlobalVariable']);//全局变量
        $this->smarty->registerPlugin('block', 'attrcontent', [$this, 'getContentFlag']);//内容属性
        $this->smarty->registerPlugin('block', 'poster', [$this, 'getPoster']);//广告
        $this->smarty->registerPlugin('block', 'navigate', [$this, 'getNavigate']);//导航
        $this->smarty->registerPlugin('function', 'crumb', [$this, 'getCrumbs']);//面包屑
        $this->smarty->registerPlugin('block', 'category', [$this, 'getCategory']);//分类列表
        $this->smarty->registerPlugin('block', 'list', [$this, 'getContentList']);//内容列表
        $this->smarty->registerPlugin('block', 'detail', [$this, 'getContentDetail']);//内容详情
        $this->smarty->registerPlugin('function', 'prev', [$this, 'getPrev']);//上一个
        $this->smarty->registerPlugin('function', 'next', [$this, 'getNext']);//下一个
    }

    /*取出核心数据*/
    public function getCoreConfig($params)
    {
        $tag = isset($params['name'])?$params['name']:'';
        $coreArr = ['pc_url', 'mobile_url', 'logo', 'hotline', 'icp', 'traffic_statistics'];
        $basicArr = ['website_name', 'seo_title', 'seo_keyword', 'seo_describe', 'copyright'];
        /*判断 参数是否在核心数据内*/
        if(in_array($tag, $coreArr)){
            $coreConfig = CoreConfig::find()->select($tag)
                            ->where('app_id = :app_id', [':app_id' => $this->app_id])
                            ->asArray()->one();
            if($tag == 'logo'){//logo图片可能会有多个，如果传index参数，按照index值返回，如果没有，则全部返回
                if(!empty($coreConfig[$tag])){
                    $tmp = explode(',', $coreConfig[$tag]);
                    if(isset($params['index']) and $params['index'] < count($tmp)){
                        $coreConfig[$tag] = $tmp[$params['index']];
                    }
                }
            }
            return $coreConfig[$tag];
        }
        /*判断 参数是否在基础数据内， 需要判断当前的语言*/
        if(in_array($tag, $basicArr)){
            $basicConfig = BasicConfig::find()->select($tag)
                            ->where('app_id = :app_id and lang = :lang', [':app_id' => $this->app_id, ':lang' => $this->lang])
                            ->asArray()->one();
            return $basicConfig[$tag];
        }

        return '';
    }

    /*取出全局变量*/
    public function getGlobalVariable($params)
    {
        $res = '';
        $tag = isset($params['name'])?$params['name']:'';
        $globalVariable = GlobalVariable::find()->select('variable_val')
                        ->where('app_id = :app_id and lang = :lang and variable_tag = :tag', [':app_id' => $this->app_id, ':lang' => $this->lang, ':tag' => $tag])
                        ->asArray()->one();
        if(!empty($globalVariable)){
            $res = $globalVariable['variable_val'];
        }
        return $res;
    }

    /*属性内容*/
    public function getContentFlag($params, $content)
    {
        if(isset($params['flag'])){
            $flag = $params['flag'];
        }else{
            return  '';
        }
        if(isset($params['page'])){
            $currPage = intval($params['page'])?$params['page']:1;
        }else{
            $currPage = 1;
        }
        if(isset($params['pageSize'])){
            $pageSize = intval($params['pageSize'])?$params['pageSize']:Tool::getPageSize();
        }else{
            $pageSize = Tool::getPageSize();
        }
        // var_dump($pageSize);

        $params['app_id'] = $this->app_id;
        $params['lang'] = $this->lang;
        $params['state'] = 3;
        $params['display'] = 2;
        $search = (new ContentSearch())->search($params);
        $contentList = $search->select(['content_id as id', 'catid', 'title', 'titlecolor as color', 'flag', 'pc_preview_count as pc_count', 'mobile_preview_count as mobile_count', 'add_time'])
                          ->with('category')
                          ->andWhere(new Expression("FIND_IN_SET(:flag, flag)", [":flag" => $flag]))
                          ->offset($pageSize*($currPage-1))->limit($pageSize)
                          ->asArray()->all();
        // P($contentList);
       
        $res = '';
        if(!empty($contentList)){
            //  /*收集所有分类ID, 为了获取分类别名，得出URL 注释原因：用了联合查询了 ->with('category')*/
            // $cateId = [];
            // foreach($contentList as $k => $v){
            //     if(!in_array($v['catid'], $cateId)){
            //         array_push($cateId, $v['catid']);
            //     }
            // }
            // $contentCategory = ContentCategory::find()->select(['catid', 'alias'])
            //                     ->where(['in', 'catid', $cateId])
            //                     ->asArray()->all();
            // // P($contentCategory);
            // foreach($contentList as $k => $v){
            //     foreach($contentCategory as $k1 => $v1){
            //         if($v['catid'] == $v1['catid']){
            //             $contentList[$k]['alias'] = $v1['alias'];
            //         }
            //     }
            // }
            // P($contentList);

            /*排序*/
            $contentFlag = ContentFlag::find()->select(['zhsorts', 'ensorts', 'jpsorts', 'krsorts'])
                            ->where('app_id = :app_id and flag = :flag', [':app_id' => $this->app_id, ':flag' => $flag])
                            ->asArray()->one();
            // P($contentFlag[$this->lang . 'sorts']);
            $langsorts = $this->lang . 'sorts';
            if(!empty($contentFlag[$langsorts])){
                $sorts = explode(',', $contentFlag[$langsorts]);
                $sortList = [];
                foreach($sorts as $k => $v){
                    foreach($contentList as $k1 => $v1){
                        if($contentList[$k1]['id'] == $v){
                            array_push($sortList, $contentList[$k1]);
                            unset($contentList[$k1]);
                        }
                    }
                }
                $contentList = $sortList;
            }
            // P($contentList);

            /*标签替换*/
            foreach($contentList as $k => $v){
                /*判断当传语言参数 为了替换url的时候，把语言带上*/
                $langWhere = '/';
                if($this->lang !== 'zh'){
                    $langWhere = '/' . $this->lang . '/';
                }

                $tmp = '';
                $tmp = str_replace("[field:count]", $v['pc_count'] + $v['mobile_count'], $content);
                $tmp = str_replace("[field:title]", $v['title'], $tmp);
                $tmp = str_replace("[field:color]", $v['color'], $tmp);
                $tmp = str_replace("[field:url]", $langWhere . $v['category']['alias'] . '/article/' . $v['id'], $tmp);
                $tmp = str_replace("[field:time]", $v['add_time'], $tmp);
                unset($contentList[$k]['category']);
                $res = $res . $tmp;
            }
            // P($contentList);
        }

        return $res;
    }

    /*
    广告列表
    $smarty, &$repeat  这两个参数主要是防止调用两次，增战展现量的时候，需要判断，否则会增加两次
    */
    public function getPoster($params, $content, $smarty, &$repeat)
    {
        $res = '';
        if(isset($params['location'])){
            $location = $params['location'];
        }else{
            return  '';
        }
        $time = date('Y-m-d H:i:s');
        $posterList = Poster::find()
                    ->select(['id', 'name', 'preview', 'url', 'url_target'])
                    ->where('app_id = :app_id and location = :location and lang = :lang and (start_time < :time and end_time > :time) and display = 2', [':app_id' => $this->app_id, ':location' => $location, ':lang' => $this->lang, ':time' => $time])
                    ->orderBy(['sort' => SORT_DESC, 'id' => SORT_DESC])
                    ->asArray()->all();
        // p($posterList);
        if(!empty($posterList)){
            $isMobile = Tool::isMobile();//判断是否手机访问
            /*标签替换*/
            foreach($posterList as $k => $v){
                /*更新展示量*/
                if($repeat){
                    if($isMobile){
                        Poster::updateAllCounters(['mobile_show_count' => 1], 'id = :id', [':id' => $v['id']]);
                    }else{
                        Poster::updateAllCounters(['pc_show_count' => 1], 'id = :id', [':id' => $v['id']]);
                    }
                }
                    
                $tmp = '';
                $tmp = str_replace("[field:title]", $v['name'], $content);
                if($v['preview'] != ''){
                    $preview = explode(',', $v['preview']);
                    // P($preview);
                    foreach($preview as $k1 => $v1){
                        if($k1 == 0){//不带索引的，按第一个处理
                            $tmp = str_replace("[field:preview]", $v1, $tmp);
                            $tmp = str_replace("[field:preview-" . $k1 . "]", $v1, $tmp);
                        }else{
                            $tmp = str_replace("[field:preview-" . $k1 . "]", $v1, $tmp);
                        }
                    }
                }
                $tmp = str_replace("[field:url]", '/poster/' . $v['id'], $tmp);
                if($v['url_target'] == 1){
                    $target = '_self';
                }else{
                    $target = '_blank';
                }
                $tmp = str_replace("[field:target]", $target, $tmp);
                $res = $res . $tmp;
            }
        }
        return  $res;
    }

    /*导航列表*/
    public function getNavigate($params, $content, $template)
    {
        /*获取category参数 主要是为了高亮菜单*/
        $activeId = 0;
        if(isset($_GET['category']) and !empty($_GET['category'])){
            $alias = $_GET['category'];
            $nav = Nav::find()->select('navid')
                        ->where('url = :url', [':url' => $alias])
                        ->orderBy(['level' => SORT_DESC])
                        ->one();
            // p($nav);
            if(!empty($nav)){
                $activeId = $nav->navid;
            }
        }

        if(isset($params['id'])){
            $parentid = intval($params['id'])?$params['id']:0;
        }else{
            $parentid = 0;
        }
        /*排除的导航*/
        if(isset($params['out'])){
            $out = $params['out']?explode(',', $params['out']):[];
        }else{
            $out = [];
        }

        $res = '';
        $navList = Nav::find()
        ->select(['navid as id', 'name', 'parentid', 'child', 'allchildid', 'preview', 'catid', 'url', 'url_target', 'args'])
        ->andWhere('app_id = :app_id and lang = :lang and display = 2 and parentid = :parentid', [':app_id' => $this->app_id, ':lang' => $this->lang, ':parentid' => $parentid])
        ->andWhere(['not in', 'navid', $out])
        ->orderBy(['sort' => SORT_ASC])
        ->asArray()->all();
        foreach($navList as $k => $v){
            $navList[$k]['child'] = ($v['child'] == 1)?false:true;//是否有子导航
            $navList[$k]['url'] = ($this->lang == '' or $this->lang == 'zh')?$navList[$k]['url']:'/' . $this->lang . '/' . $navList[$k]['url'];//带语言的链接

            /*高亮菜单*/
            $tmp = explode(',', $v['allchildid']);
            if($activeId > 0 and (in_array($activeId, $tmp) or $activeId == $v['id'])){
                $navList[$k]['active'] = true;
            }else{
                $navList[$k]['active'] = false;
            }
        }
        $template->assign("list", $navList);
        return $content;
        // P($navList);
    }

    /*面包屑*/
    public function getCrumbs($params)
    {
        /*先看是否有 分类id 形参 如果有就直接调取，如果没有，就调取 url传的值*/
        $catid = 0;
        if(isset($params['id'])){
            $catid = intval($params['id'])?$params['id']:0;
        }
        if($catid == 0){
            if(isset($_GET['category']) and !empty($_GET['category'])){
                $alias = $_GET['category'];
                $contentCategory = ContentCategory::find()->select(['name', 'catid'])
                            ->andWhere('app_id = :app_id and lang = :lang and display = 2 and alias = :alias', [':app_id' => $this->app_id, ':lang' => $this->lang, ':alias' => $alias])
                            ->one();
                if(!empty($contentCategory)){
                    $catid = $contentCategory->catid;
                    $self = $contentCategory->name;
                }
                // p($catid);
            }
        }

        $res = '';
        $divide = isset($params['divide'])?$params['divide']:'/';
        if($catid > 0){
            $contentCategory = ContentCategory::find()
                            ->select(['catid', 'name', 'alias', 'allparentid', 'outside', 'url_target', 'outside_url'])
                            ->andWhere('app_id = :app_id and display = 2 and catid = :catid', [':app_id' => $this->app_id, ':catid' => $catid])
                            ->one();
            if(!empty($contentCategory)){
                // P($contentCategory);
                if($contentCategory->allparentid != '0'){
                    $parentids = $contentCategory->allparentid;//所有父级ID
                    $parentidsArr = explode(',', $parentids);
                    // P($parentidsArr);
                    foreach($parentidsArr as $k => $v){
                        if($v > 0){
                            $contentCategory = ContentCategory::find()
                                ->select(['catid', 'name', 'alias', 'allparentid', 'outside', 'url_target', 'outside_url'])
                                ->andWhere('app_id = :app_id and display = 2 and catid = :catid', [':app_id' => $this->app_id, ':catid' => $v])
                                ->one();
                            $target = ($contentCategory->outside == 2 and $contentCategory->url_target == 2)?' target=_blank':'';
                            if($k < count($parentidsArr) - 1){
                                $res = $res . '<a href="' . $contentCategory->alias . '"' . $target . '>' . $contentCategory->name . '</a>' . $divide;
                            }else{
                                $res = $res . '<a href="' . $contentCategory->alias . '"' . $target . '>' . $contentCategory->name . '</a>';
                            }
                        }
                    }
                    $res = $res . $divide . $self;
                }else{
                    $res = $self;
                }
            }
        }
        return $res;
    }

    /*分类列表*/
    public function getCategory($params, $content, $template)
    {
        /*获取category参数 主要是为了高亮菜单,二是为了 没有传id的时候，取菜url上菜单ID对应的栏目*/
        $activeId = 0;
        $parentid = 0;
        $title = '';
        if(isset($_GET['category']) and !empty($_GET['category'])){
            $alias = $_GET['category'];
            $contentCategory = ContentCategory::find()->select(['catid', 'parentid'])
                        ->where('alias = :alias and lang = :lang', [':alias' => $alias, ':lang' => $this->lang])
                        ->one();
            // p($catid);
            if(!empty($contentCategory)){
                $activeId = $contentCategory->catid;
                $parentid = $contentCategory->parentid;
            }
        }

        /*如果有传入值，则优先使用传入的值*/
        if(isset($params['id'])){
            $parentid = intval($params['id'])?$params['id']:0;
        }

        /*取出标题*/
        if($parentid > 0){
            $contentCategory = ContentCategory::find()->select('name')
                            ->where('catid = :catid', [':catid' => $parentid])
                            ->one();
            if(!empty($contentCategory)){
                $title = $contentCategory->name;
            }
        }

        /*排除的导航*/
        if(isset($params['out'])){
            $out = $params['out']?explode(',', $params['out']):[];
        }else{
            $out = [];
        }

        $res = '';
        $contentCategoryList = ContentCategory::find()
        ->select(['catid as id', 'name', 'alias', 'preview', 'parentid', 'allparentid', 'child', 'allchildid', 'outside', 'url_target', 'outside_url'])
        ->andWhere('app_id = :app_id and lang = :lang and display = 2 and parentid = :parentid', [':app_id' => $this->app_id, ':lang' => $this->lang, ':parentid' => $parentid])
        ->andWhere(['not in', 'catid', $out])
        ->orderBy(['sort' => SORT_ASC])
        ->asArray()->all();
        foreach($contentCategoryList as $k => $v){
            $contentCategoryList[$k]['child'] = ($v['child'] == 1)?false:true;//是否有子分类
            /*URL*/
            if($v['outside'] == 2 and !empty($v['outside_url'])){
                $contentCategoryList[$k]['url'] = ($this->lang == '' or $this->lang == 'zh')?$v['outside_url']:'/' . $this->lang . '/' . $v['outside_url'];//带语言的链接
            }else{
                $contentCategoryList[$k]['url'] = ($this->lang == '' or $this->lang == 'zh')?'/' . $v['alias']:'/' . $this->lang . '/' . $v['alias'];//带语言的链接
            }

            /*预览图*/
            if($v['preview'] != ''){
                $contentCategoryList[$k]['preview'] = explode(',', $v['preview']);
            }

            /*高亮菜单*/
            $tmp = explode(',', $v['allchildid']);
            if($activeId > 0 and (in_array($activeId, $tmp) or $activeId == $v['id'])){
                $contentCategoryList[$k]['active'] = true;
            }else{
                $contentCategoryList[$k]['active'] = false;
            }
        }
        $template->assign("list", $contentCategoryList);
        $template->assign("title", $title);
        return $content;
        // P($contentCategoryList);
    }

    /*内容列表*/
    public function getContentList($params, $content, $template)
    {
        $res = '';
        $catid = 0;
        $title = '';
        $params['app_id'] = $this->app_id;
        if(isset($params['id'])){
            $catid = intval($params['id'])?$params['id']:0;
        }

        if(isset($_GET['page'])){
            $currPage = intval($_GET['page'])?$_GET['page']:1;
        }else{
            $currPage = 1;
        }
        if(isset($params['pageSize'])){
            $pageSize = intval($params['pageSize'])?$params['pageSize']:Tool::getPageSize();
        }else{
            $pageSize = Tool::getPageSize();
        }
        // P($pageSize);
        /*如果没有传ID, 从URL参数中获取*/
        if($catid == 0){
            if(isset($_GET['category']) and !empty($_GET['category'])){
                $alias = $_GET['category'];
                $contentCategory = ContentCategory::find()->select(['catid', 'name'])
                            ->where('alias = :alias and app_id = :app_id and lang = :lang', [':alias' => $alias, ':app_id' => $this->app_id, ':lang' => $this->lang])
                            ->one();
                // p($catid);
                if(!empty($contentCategory)){
                    $catid = $contentCategory->catid;
                    $title = $contentCategory->name;
                }
            }
        }
        // P($catid);
        // P($params);
        $search = (new ContentSearch())->search($params);
        $count = $search->andWhere('catid = :catid', [':catid' => $catid])->count();
        $contentList = $search->select(['content_id as id', 'catid', 'title', 'titlecolor as color', 'describe', 'preview', 'flag', 'pc_preview_count as pc_count', 'mobile_preview_count as mobile_count', 'add_time as time'])
                          ->with('category')
                          ->andWhere('catid = :catid and display = 2 and state = 3', [':catid' => $catid])
                          ->orWhere(new Expression("FIND_IN_SET(:catids, catids) and display = 2 and state = 3 and app_id = :app_id and lang = :lang", [":catids" => $catid, ':app_id' => $this->app_id, ':lang' => $this->lang]))
                          ->orderBy([
                                    'istop' => SORT_DESC,
                                    'toptime' => SORT_DESC,
                                    'sort' => SORT_DESC,
                                    'add_time' => SORT_DESC
                                ])
                          ->offset($pageSize*($currPage-1))->limit($pageSize)
                          // ->createCommand()->getRawSql();
                          ->asArray()->all();
        // P($contentList);
        // P($catid);
        if(!empty($contentList)){
            foreach($contentList as $k => $v){
                $lang = ($this->lang == '' or $this->lang == 'zh')?'/':'/' . $this->lang . '/';
                $contentList[$k]['url'] = $lang . $v['category']['alias'] . '/article/' . $v['id'];

                if($v['preview'] != ''){
                    $contentList[$k]['preview'] = explode(',', $v['preview']);
                }
                $timestamp = strtotime($v['time']);
                $contentList[$k]['day'] = date('d', $timestamp);
            }
        }
        // P($contentList);
        $template->assign("list", $contentList);
        $template->assign("title", $title);
        /*分页样式*/
        $page = new Page($count, $this->lang);
        $show = [3, 4, 5, 6, 7];
        if(isset($params['pageshow'])){
            switch ($params['pageshow']) {
                case 'a':
                    $show = [4, 6];
                    break;
                case 'b':
                    $show = [4, 5, 6];
                    break;
                case 'c':
                    $show = [3, 5, 7];
                    break;
                case 'd':
                    $show = [4, 5, 6, 8];
                    break;
                case 'e':
                    $show = [3, 5, 7, 8];
                    break;

                default:
                    break;
            }
        }
        $template->assign("page", $page->fpage($show));

        return $content;
    }

    /*内容详情*/
    public function getContentDetail($params, $content, $template, &$repeat)
    {
        $content_id = 0;
        if(isset($params['id'])){
            $content_id = intval($params['id'])?$params['id']:0;
        }
        // P($content_id);
        $isMobile = Tool::isMobile();//判断是否手机访问

        /*如果没有传ID值、且URL中ID没有值 URL中 ategory传值了，说明是取单页内容（后台必须是单页才行），如果是字符串，说明是别名，需要转成ID*/
        if($content_id == 0 and isset($_GET['category']) and !isset($_GET['id'])){
            if(!is_numeric($_GET['category'])){
                $contentCategory = ContentCategory::find()->select('catid')
                            ->andWhere('app_id = :app_id and lang = :lang and display = 2 and alias = :alias', [':app_id' => $this->app_id, ':lang' => $this->lang, ':alias' => $_GET['category']])
                            ->one();
                if(!empty($contentCategory)){
                    // $_GET['category'] = $contentCategory->catid;
                    $catid = $contentCategory->catid;
                }
            }

            $contents = Content::find()->select(['content_id', 'title', 'titlecolor', 'preview', 'url_target', 'outside_url', 'source', 'author', 'keyword', 'describe', 'content', 'pc_preview_count', 'mobile_preview_count', 'add_time'])
                ->andWhere('catid = :catid and app_id = :app_id and display = 2 and state = 3', [':catid' => $catid, ':app_id' => $this->app_id])
                ->orderBy([
                        'istop' => SORT_DESC,
                        'toptime' => SORT_DESC,
                        'sort' => SORT_DESC,
                        'add_time' => SORT_DESC
                    ])
                ->one();
            // P($contents);
            /* 增加阅读量 */
            if(!is_null($contents)) {
                $id = $contents->content_id;
                if($repeat){
                    if($isMobile){
                        Content::updateAllCounters(['mobile_preview_count' => 1], 'content_id = :id', [':id' => $id]);
                    }else{
                        Content::updateAllCounters(['pc_preview_count' => 1], 'content_id = :id', [':id' => $id]);
                    }
                }
            }
        }

        /*如果没有传ID 在URL中获取*/
        if($content_id == 0 and isset($_GET['id'])){
            $content_id = intval($_GET['id'])?$_GET['id']:0;
        }

        if($content_id > 0 and !isset($contents)){
            // P($content_id);
            $contents = Content::find()->select(['content_id', 'title', 'titlecolor', 'preview', 'url_target', 'outside_url', 'source', 'author', 'keyword', 'describe', 'content', 'pc_preview_count', 'mobile_preview_count', 'add_time'])
                ->andWhere('content_id = :content_id and app_id = :app_id and display = 2 and state = 3', [':content_id' => $content_id, ':app_id' => $this->app_id])
                ->orderBy([
                        'istop' => SORT_DESC,
                        'toptime' => SORT_DESC,
                        'sort' => SORT_DESC,
                        'add_time' => SORT_DESC
                    ])
                ->one();
            // P($contents);
            /* 增加阅读量 */
            if(!is_null($contents)) {
                if($repeat){
                    if($isMobile){
                        Content::updateAllCounters(['mobile_preview_count' => 1], 'content_id = :id', [':id' => $content_id]);
                    }else{
                        Content::updateAllCounters(['pc_preview_count' => 1], 'content_id = :id', [':id' => $content_id]);
                    }
                }
            }
        }
        // P($contents);
        $title = '';
        $titlecolor = '';
        $preview = '';
        $url_target = '';
        $outside_url = '';
        $source = '';
        $author = '';
        $keyword = '';
        $describe = '';
        $contentshow = '';
        $pc_count = '';
        $mobile_count = '';
        $add_time = '';
            // P($contents);
        if(isset($contents)){
            $title = $contents->title;
            $titlecolor = $contents->titlecolor;
            if(!empty($contents->preview)){
                $preview = explode(',', $contents->preview);
            }else{
                $preview = [];
            }
            $url_target = $contents->url_target;
            $outside_url = $contents->outside_url;
            $source = $contents->source;
            $author = $contents->author;
            $keyword = $contents->keyword;
            $describe = $contents->describe;
            $contentshow = Html::decode($contents->content);
            $pc_count = $contents->pc_preview_count;
            $mobile_count = $contents->mobile_preview_count;
            $add_time = $contents->add_time;
        }
        $template->assign("title", $title);
        $template->assign("titlecolor", $titlecolor);
        $template->assign("preview", $preview);
        // $template->assign("url_target", $url_target);
        // $template->assign("outside_url", $outside_url);
        $template->assign("source", $source);
        $template->assign("author", $author);
        $template->assign("keyword", $keyword);
        $template->assign("describe", $describe);
        $template->assign("content", $contentshow);
        $template->assign("pc_count", $pc_count);
        $template->assign("mobile_count", $mobile_count);
        $template->assign("add_time", $add_time);
        // P($contents);
        return $content;
    }

    /*上一篇*/
    public function getPrev($params)
    {
        if(isset($params['flag']) and $params['flag'] == 'title'){
            $flag = 'title';
        }
        if(isset($params['flag']) and $params['flag'] == 'url'){
            $flag = 'url';
        }
        $res = $this->getContent('prev', $flag);
        return $res;
    }

    /*下一篇*/
    public function getNext($params)
    {
        if(isset($params['flag']) and $params['flag'] == 'title'){
            $flag = 'title';
        }
        if(isset($params['flag']) and $params['flag'] == 'url'){
            $flag = 'url';
        }
        $res = $this->getContent('next', $flag);
        return $res;
    }

    /*上一篇 下一篇 调此函数*/
    private function getContent($type, $flag)
    {
        $content_id = 0;
        if(isset($_GET['id'])){
            $content_id = intval($_GET['id'])?$_GET['id']:0;
        }
        if(isset($params['id'])){
            $content_id = intval($params['id'])?$params['id']:0;
        }
        $res = '';
        if($content_id > 0){
            $self = Content::find()->select(['content_id as id', 'catid', 'istop', 'toptime', 'sort', 'add_time'])
                ->andWhere('content_id = :content_id and app_id = :app_id and display = 2 and state = 3', [':content_id' => $content_id, ':app_id' => $this->app_id])
                ->with('category')
                ->one();
            // P($self);
            if(!empty($self)){
                $catid = $self->catid;
                $alias = $self->category->alias;
                // P($alias);
                if($type == 'prev'){
                    $where = '(istop >= ' . $self->istop . ' and toptime >= "' . $self->toptime . '" and sort > ' . $self->sort . ') and catid = ' . $catid;
                    // $where = 'catid = ' . $catid;
                }
                if($type == 'next'){
                    $where = '(istop <= ' . $self->istop . ' and toptime <= "' . $self->toptime . '" and sort < ' . $self->sort . ') and catid = ' . $catid;
                }
                // P($where);
                $sql = "select content_id as id, catid, title, titlecolor, url_target, outside_url, istop, toptime, sort, add_time from su_cms_content where " . $where . ' and app_id = :app_id and display = 2 and state = 3 order by istop desc, toptime desc, sort desc, add_time desc';
                // P($sql);
                if($type == 'prev'){
                    $sql = "select * from (" . $sql . ") as t order by istop asc, toptime asc, sort asc, add_time asc";
                }
                if($type == 'next'){
                    $sql = "select * from (" . $sql . ") as t order by istop desc, toptime desc, sort desc, add_time desc";
                }
                // P($sql);
                $contents = Content::findBySql($sql,[':app_id' => $this->app_id])->asArray()->one();;
                // P($contents);
                if(!empty($contents)){
                    $lang = ($this->lang == '' or $this->lang == 'zh')?'':'/' . $this->lang;
                    $contents['url'] = $lang . '/' . $alias . '/article/' . $contents['id'];
                    $res = $contents[$flag];
                }
            }
            // P($res);
        }
        if($res == '' and $flag == 'title'){
            $res = '没有了！';
        }
        return $res;
    }

    /*获取分类名称*/

    public function P($arr)
    {
        echo '<pre>';
        var_dump($arr);
        echo '</pre>';
        die;
    }
}